﻿using Kingdee.BOS.App;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Business.Bill.Utils;
using Kingdee.BOS.BusinessEntity.ConvertTracker;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.ConvertElement;
using Kingdee.BOS.Core.Metadata.ConvertElement.ServiceArgs;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;


namespace K.KDL
{
    [Description("应收单表单服务插件")]
    public class CustomArFormPlugin : AbstractDynamicFormPlugIn
    {
        //FormMetadata _arMeta;

        public override void BarItemClick(BarItemClickEventArgs e)
        {
            base.BarItemClick(e);

            if (e.BarItemKey == "tbSpecialDraw")
            {
                SpecialDraw();
            }
        }

        private void SpecialDraw()
        {
            var showParam = new DynamicFormShowParameter();
            showParam.FormId = "SHKD_ArMatchStencil";
            showParam.ParentPageId = this.View.PageId;
            showParam.OpenStyle.ShowType = ShowType.Floating;
            //目标模型可以在其表单插件中的OnInitial事件中获取这些参数
            showParam.CustomComplexParams.Add("OrgId", this.View.Model.DataObject["SETTLEORGID_Id"]);
            showParam.CustomComplexParams.Add("CustId", this.View.Model.DataObject["CUSTOMERID_Id"]);

            this.View.ShowForm(showParam,
                (result) =>
                {
                    if (result == null) return;
                    var returndata = result.ReturnData as List<ListSelectedRow>;
                    if (returndata == null) return;
                    //对返回的数据做业务处理
                    var osSelectedRows = returndata.Where(_ => _.FormID == "SAL_OUTSTOCK")?.ToList();
                    // TP_DeliveryToreceivable
                    //var osRule = ConvertServiceHelper.GetConvertRules(Context, "SAL_OUTSTOCK", "AR_receivable").FirstOrDefault(_ => _.IsDefault);
                    // TP_DeliveryToreceivable
                    var osRule = ConvertServiceHelper.GetConvertRules(Context, "SAL_OUTSTOCK", "AR_receivable").FirstOrDefault(_ => _.IsDefault);
                    if (osSelectedRows.Count() > 0) RunDraw(osRule, osSelectedRows);
                    //if (osSelectedRows.Count() > 0) DoDraw(osRule, osSelectedRows);

                    var rsSelectedRows = returndata.Where(_ => _.FormID == "SAL_RETURNSTOCK")?.ToList();
                    //var rsRule = ConvertServiceHelper.GetConvertRules(Context, "SAL_RETURNSTOCK", "AR_receivable").FirstOrDefault(_ => _.IsDefault);
                    // AR_ReturnToReceivableMap
                    var rsRule = ConvertServiceHelper.GetConvertRules(Context, "SAL_RETURNSTOCK", "AR_receivable").FirstOrDefault(_ => _.IsDefault);
                    if (rsSelectedRows.Count() > 0) RunDraw(rsRule, rsSelectedRows);
                    //if (rsSelectedRows.Count() > 0) DoDraw(rsRule, rsSelectedRows);
                }
            );
        }

        private void RunDraw(ConvertRuleElement rule, List<ListSelectedRow> listSelectedRowCollection)
        {
            var view = this.View;

            //ListSelectedRowCollection listSelectedRowCollection = returnData as ListSelectedRowCollection;
            if (listSelectedRowCollection != null && listSelectedRowCollection.Count > 0)
            {
                view.Model.ClearNoDataRow();
                object cloneObj = view.Model.DataObject.Clone(false, true);
                var selectedRows = listSelectedRowCollection.ToArray();
                bool isSuccess = false;
                try
                {
                    var drawArgs = new DrawArgs(rule, view.Model.DataObject, selectedRows);
                    //drawArgs.ConvertFilter = conventFilter;
                    drawArgs.CustomParams = new Dictionary<string, object>();
                    var option = OperateOption.Create();
                    // 是否按单据
                    //option.SetVariableValue("SelectByBillId", retInfo.SelectByBillId);
                    if (view.Session.ContainsKey("ControlFieldTakeParam"))
                    {
                        option.SetVariableValue("ControlFieldTakeParam", view.Session["ControlFieldTakeParam"]);
                    }
                    var convertOperationResult = ConvertServiceHelper.Draw(view.Context, drawArgs, option);
                    if (convertOperationResult.TargetDataEntities != null && convertOperationResult.TargetDataEntities.Count() > 0)
                    {
                        ((BillOpenParameter)view.OpenParameter).CreateFrom = CreateFrom.Draw;
                        view.Model.DataObject = convertOperationResult.TargetDataEntities.First().DataEntity;
                        view.Model.ClearNoDataRow();
                        view.UpdateView();
                        view.Model.DataChanged = true;
                        isSuccess = true;
                        if (convertOperationResult.ValidationErrors != null && convertOperationResult.ValidationErrors.Count > 0)
                        {
                            string msg = string.Join(";\r\n", from t in convertOperationResult.ValidationErrors
                                                              select t.Message);
                            view.ShowWarnningMessage(msg, "", MessageBoxOptions.OK, null, MessageBoxType.Advise);
                        }
                    }
                }
                catch (Kingdee.BOS.KDExceptionValidate kDExceptionValidate)
                {
                    view.ShowErrMessage(kDExceptionValidate.Message, kDExceptionValidate.ValidateString, MessageBoxType.Notice);
                }
                catch (Kingdee.BOS.KDException ex)
                {
                    view.ShowErrMessage(ex.Message, "", MessageBoxType.Notice);
                }
                finally
                {
                    if (!isSuccess)
                    {
                        if (view.Model.DataObject.DataEntityState.FromDatabase)
                        {
                            ((IBillModel)view.Model).Load(view.Model.DataObject["ID"]);
                        }
                        else
                        {
                            view.Model.DataObject = (DynamicObject)cloneObj;
                            view.UpdateView();
                        }
                    }
                }
            }
        }

        private void DoDraw(ConvertRuleElement rule, List<ListSelectedRow> listSelectedRowCollection)
        {
            var orgId = Convert.ToInt64(this.View.Model.DataObject["SETTLEORGID_Id"]);
            var opFormReturnInfo = new OpFormReturnInfo(this.View.GetFormId(), string.Empty, orgId);
            opFormReturnInfo.ShowFilter = false;
            //opFormReturnInfo.FilterSchemeId = 
            //opFormReturnInfo.EntryUpperLimitValue = entryUppperLimitValue;
            opFormReturnInfo.SelectedRows = listSelectedRowCollection.ToArray();
            opFormReturnInfo.Rule = rule;
            opFormReturnInfo.RealSourceFormId = rule.SourceFormId;

            var option = OperateOption.Create();
            option.SetVariableValue("ConvertType", "Draw");
            this.View.DoDraw(opFormReturnInfo, option);
        }
    }
}
